package com.xdf.springsecuritydemo.service.security;

import com.xdf.springsecuritydemo.utils.SpringSecurityUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.naming.AuthenticationNotSupportedException;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Optional;

/**
 * @author chanchaw
 * @create 2025-10-09 13:46
 */
@Service
public class MyAuthenticationServiceImpl implements MyAuthenticationService{
    public Boolean hasPermission(HttpServletRequest req) throws AuthenticationNotSupportedException {
        UserDetails currentUserDetails = SpringSecurityUtils.getCurrentUserDetails();
        if(currentUserDetails == null) throw new AuthenticationNotSupportedException("请登录后再访问！");

        Collection<? extends GrantedAuthority> authorities = currentUserDetails.getAuthorities();
        if(authorities.size() == 0) throw new AuthenticationNotSupportedException("没有访问权限！");

        String requestURI = Optional.ofNullable(req.getRequestURI()).orElse("");
        SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(requestURI);
        boolean contains = authorities.contains(simpleGrantedAuthority);
        return contains;
    }

    public Boolean hasRole(String role){
        return SpringSecurityUtils.hasRole(role);
    }
}
